<?php

namespace App\Http\Controllers\Api;

use App\Models\OrderShirt;
use function EasyWeChat\Kernel\Support\generate_sign;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;

class OrderShirtController extends Controller
{
    public function store(Request $request)
    {
        $auth = $this->checkToken($request);
        if (!$auth['auth']) {
            return response()->json($auth['data']);
        }
        $openid = $auth['openid'];
        $validator = $this->beforeStoreValidator($request);
        if ($validator->fails()) {
            return response()->json([
                'status' => 'failed',
                'code' => 0,
                'error' => $validator->errors()
            ]);
        }
        $orderShirt = new OrderShirt;

        $orderShirt->order_number = generateOrderNumber();
        $orderShirt->shipping = (OrderShirt::SHIPPING) / 100;
        $orderShirt->order_amount = (OrderShirt::ORDER_AMOUNT) / 100;
        $orderShirt->amount = (OrderShirt::AMOUNT) / 100;
        $orderShirt->order_from = 'wechat-mini';
        $orderShirt->openid = $openid;
        $orderShirt->unionid = '';
        $orderShirt->wechat_nickname = $request->input('wechat_nickname', '');
        $orderShirt->shirt_mianliao = $request->input('shirt_mianliao');
        $orderShirt->shirt_lingxing = $request->input('shirt_lingxing');
        $orderShirt->shirt_xiuxing = $request->input('shirt_xiuxing');
        $orderShirt->shirt_xiuzi = $request->input('shirt_xiuzi');
        $orderShirt->shirt_xiuzicolor = $request->input('shirt_xiuzicolor', '');
        $orderShirt->shirt_xiuzicontent = $request->input('shirt_xiuzicontent', '');
        $orderShirt->height = $request->input('height');
        $orderShirt->weight = $request->input('weight');
        $orderShirt->shirt_xiongxing = $request->input('shirt_xiongxing');
        $orderShirt->shirt_jianxing = $request->input('shirt_jianxing');
        $orderShirt->shirt_fuxing = $request->input('shirt_fuxing');
        $orderShirt->shirt_beibu = $request->input('shirt_beibu');
        $orderShirt->recipient_phone = $request->input('recipient_phone');
        $orderShirt->recipient_name = $request->input('recipient_name');
        $orderShirt->recipient_area = $request->input('recipient_area');
        $orderShirt->recipient_address = $request->input('recipient_address');
        $orderShirt->buyer_phone = $request->input('buyer_phone');

        $saved = $orderShirt->save();
        if ($saved) {
            return response()->json([
                'status' => 'success',
                'code' => 1,
                'data' => $orderShirt,
            ]);
        } else {
            return response()->json([
                'status' => 'failed',
                'code' => 0,
                'error' => 'server error'
            ], 500);
        }
    }

    private function beforeStoreValidator($request)
    {
        $validator = Validator::make($request->all(), [
            'shirt_mianliao' => 'required|max:100',
            'shirt_lingxing' => 'required|max:100',
            'shirt_xiuxing' => 'required|max:100',
            'shirt_xiuzi' => 'required|max:100',
            'shirt_xiuzicolor' => 'max:100',
            'shirt_xiuzicontent' => 'max:100',
            'height' => 'required',
            'weight' => 'required',
            'shirt_xiongxing' => 'required|max:100',
            'shirt_jianxing' => 'required|max:100',
            'shirt_fuxing' => 'required|max:100',
            'shirt_beibu' => 'required|max:100',
            'recipient_phone' => 'required|max:11',
            'recipient_name' => 'required|max:100',
            'recipient_area' => 'required|max:100',
            'recipient_address' => 'required|max:100',
            'buyer_phone' => 'required|max:11',
        ]);

        return $validator;
    }

    private function checkToken($request)
    {
        $token = $request->header('token');
        if ($token) {
            if ($user = Cache::get($token)) {
                return [
                    'auth' => true,
                    'openid' => json_decode($user)->openid,
                ];
            } else {
                return [
                    'auth' => false,
                    'data' => [
                        'status' => 'failed',
                        'code' => 401,
                        'msg' => 'token已过期',
                    ],
                ];
            }
        } else {
            return [
                'auth' => false,
                'data' => [
                    'status' => 'failed',
                    'code' => 401,
                    'msg' => '请求缺少token',
                ],
            ];
        }
    }

    public function createPayment(Request $request)
    {
        $auth = $this->checkToken($request);
        if (!$auth['auth']) {
            return response()->json($auth['data']);
        }
        $openid = $auth['openid'];
        $order_id = $request->input('order_id');
        $order = OrderShirt::find($order_id);
        $app = app('wechat.payment');
        $result = $app->order->unify([
            'body' => '购漂亮轻定制',
            'out_trade_no' => $order->order_number,
            'total_fee' => OrderShirt::AMOUNT,
            'notify_url' => 'https://www.goupiaoliang.com/api/payment_action',
            'trade_type' => 'JSAPI',
            'openid' => $openid
        ]);

        if ($result['return_code'] === 'SUCCESS') {
            $params = [
                'appId' => config('wechat.payment.default.app_id'),
                'timeStamp' => time(),
                'nonceStr' => $result['nonce_str'],
                'package' => 'prepay_id=' . $result['prepay_id'],
                'signType' => 'MD5',
            ];

            $params['paySign'] = generate_sign($params, config('wechat.payment.default.key'));
            $params['return_code'] = $params['result_code'] = 'SUCCESS';
            $order->prepay_id = $result['prepay_id'];
            $order->save();
            return $params;
        } else {
            return $result;
        }
    }

    public function paymentAction()
    {
        $app = app('wechat.payment');
        $response = $app->handlePaidNotify(function ($message, $fail) {
            $order = OrderShirt::where('order_number', $message['out_trade_no'])->first();

            if (!$order || $order->status == 1) {
                return true;
            }

            if ($message['return_code'] === 'SUCCESS') {
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $order->status = 1;
                    $order->payment_at = time();

                    $this->sendTemplateInfo($order);
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->status = 4;
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            $order->save();

            return true;
        });

        return $response;
    }

    private function sendTemplateInfo($order)
    {
        $app = app('wechat.mini_program');
        $app->template_message->send([
            'touser' => $order->openid,
            'template_id' => 'T-Lukh99Zl9hFYoo1rYqwWafuYRMlkU-QQpnjKIsGhw',
            'page' => 'pages/index/index',
            'form_id' => $order->prepay_id,
            'data' => [
                'keyword1' => $order->created_at,
                'keyword2' => $order->order_number,
                'keyword3' => date('Y-m-d H:i:s', $order->payment_at),
                'keyword4' => '199元',
                'keyword5' => '购漂亮轻定制',
            ],
        ]);

        return true;
    }

    public function search(Request $request)
    {
        $search = $request->search;
        $o = substr($search, 0, 2);
        if (strtoupper($o) === 'HC') {
            // 订单号查询
            $orders = OrderShirt::where('status', 1)->where('order_number', strtoupper($search))->get();
            if ($orders->isEmpty()) {
                return [
                    'code' => 0
                ];
            } else {
                return [
                    'code' => 1,
                    'data' => $orders
                ];
            }
        } else {
            // 手机号查询
            $orders = OrderShirt::where('status', 1)->where('recipient_phone', $search)->get();
            if ($orders->isEmpty()) {
                return [
                    'code' => 0
                ];
            } else {
                return [
                    'code' => 1,
                    'data' => $orders
                ];
            }
        }
    }
}
